<?php

namespace App\Admin\Actions\Msg;

use App\Jobs\SendWechatMsg;
use App\Models\WechatUser;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;

class Send extends RowAction
{
    public $name = '群发';

    public function handle(Model $model)
    {
        $userList = WechatUser::query()->select('id', 'name', 'openid')
            ->where('is_subscribe', 1)->where('is_del', 0)->get();
        if ($userList->isEmpty()) {
            return $this->response()->error('暂无关注公众号的用户信息')->refresh();
        }
        foreach ($userList->toArray() as $user) {
            SendWechatMsg::dispatch([
                'user' => $user,
                'data' => $model->toArray(),
            ]);
        }
        $count = $userList->count();
        $msg = '加入发送任务成功，本次将对 ' . $count . ' 位关注用户发送消息，请稍后在消息记录列表查看';
        return $this->response()->success($msg)->refresh();
    }

    public function dialog()
    {
        $this->confirm('确定群发吗？');
    }

}
